﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Noesis.Javascript;
using System.IO;

namespace A2DFramework.JSService
{
    class Encryptor
    {
        public class MockWindow
        {
        }
        public class MockDocument
        {
        }

        private static string mainJSPath=null;
        public static string MainJSPath
        {
            get
            {
                if (mainJSPath == null || mainJSPath == string.Empty)
                    throw new Exception("Please specify MianJSPath before use Encryptor module");

                return mainJSPath;
            }
            set
            {
                mainJSPath = value;
            }
        }
        static MockWindow wnd = new MockWindow();
        static MockDocument doc = new MockDocument();

        public static string Encode(string plainText)
        {
            using (JavascriptContext context = new JavascriptContext())
            {
                context.SetParameter("window", wnd);
                context.SetParameter("document", doc);
                context.SetParameter("message", plainText);
                string js = File.ReadAllText(MainJSPath);
                js += @"
                            result = window.$.DES.encrypt(message);
";
                context.Run(js);
                string result = (string)context.GetParameter("result");
                return result;
            }
        }
        public static string Decode(string encryptedText)
        {
            using (JavascriptContext context = new JavascriptContext())
            {
                context.SetParameter("window", wnd);
                context.SetParameter("document", doc);
                context.SetParameter("encryptedMessage", encryptedText);
                string js = File.ReadAllText(MainJSPath);
                js += @"
                            result = window.$.DES.decrypt(encryptedMessage);
";
                context.Run(js);
                string result = (string)context.GetParameter("result");
                return result;
            }
        }
    }
}
